
// -----------------------------------------------------------------------------

#include "stdafx.h"
#include "Win32.IO.DirectoryCursor.h"

namespace Kif
{
namespace Win32
{
namespace IO
{

/// <summary>read the next directory entry</summary>
/// <returns>return the next directory entry</returns>
bool DirectoryCursor::Next()
{

   StartAgain:
   {  // ugly but works like a champ!

      if ((cycle && (cursorHandle == INVALID_HANDLE_VALUE)) || getFirstEntry)
      {

         // close directory if one is open

         Close() ;

         // open directory to be used

         cursorHandle = FindFirstFile(dirPath.GetBuffer(),&dirEntry);
         if (cursorHandle == INVALID_HANDLE_VALUE)
         {
            cursorHandle = INVALID_HANDLE_VALUE;
            return(false);
         }

         getFirstEntry = false;
         Count = 0;
      }
   }

   // read directory entry

   if (cursorHandle && (cursorHandle != INVALID_HANDLE_VALUE))
   {
      BOOL foundEntry = FindNextFile(cursorHandle,&dirEntry);
      if (foundEntry)
      {
         TCHAR *centry = dirEntry.cFileName ;

         // ignore / skip the '.' and '..' directories

         if (IgnoreDottedEntries) {
            if (centry[0] == '.') {
               TCHAR *pentry = centry + 1 ;
               if (*pentry == '.') {
                  pentry++ ;

                  // this will make this function to return when there are no
                  // entries on the directory, else it will loop for ever!

                  if (!(*pentry))
                     centry = NULL ;
               }
               if ((centry || (!cycle)) && !(*pentry))
                  goto StartAgain ;
            }
         }

         if (centry)
            Count++ ;
      }
      else
      {
         lastResult.ErrorNo = GetLastError();
         Close();
         if (cycle)
            goto StartAgain ;
         *dirEntry.cFileName = NULL;
      }
   }
   else
      *dirEntry.cFileName = NULL;

   return(*dirEntry.cFileName != NULL) ;
}  // end of DirectoryCursor::Next

}  // end of Kif::Win32::IO
}  // end of Kif::Win32
}  // end of Kif

